package com.rice.riceaiagent.rag;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Markdown阅读器
 * @author ricejson
 */
@Component
public class MyMarkdownReader {
    private static final Logger logger = LoggerFactory.getLogger(MyMarkdownReader.class);
    private final ResourcePatternResolver resolver;

    public MyMarkdownReader(ResourcePatternResolver resolver) {
        this.resolver = resolver;
    }

    public List<Document> loadMarkdowns(){
        List<Document> documents = new ArrayList<>();
        try {
            Resource[] resources = this.resolver.getResources("classpath:document/*.md");
            for (Resource resource : resources) {
                // 准备DocumentReaderConfig
                String filename = resource.getFilename();
                MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
                        .withHorizontalRuleCreateDocument(true)
                        .withIncludeCodeBlock(false)
                        .withIncludeBlockquote(true)
                        .withAdditionalMetadata("filename", filename)
                        .build();
                // 创建DocumentReader
                MarkdownDocumentReader reader = new MarkdownDocumentReader(resource, config);
                documents.addAll(reader.get());
            }
        } catch (IOException e) {
            logger.error("markdown 文档加载失败！");
        }
        return documents;
    }
}
